<template>
  <view class="container">
    <view class="header">
      <text class="header-title">编辑地址</text>
    </view>

    <view class="section">
      <!-- 收货人姓名 -->
      <view class="form-item">
        <text class="label">收货人</text>
        <input class="input" placeholder="请输入收货人姓名" v-model="name" />
      </view>

      <!-- 手机号码 -->
      <view class="form-item">
        <text class="label">手机号码</text>
        <input class="input" type="number" placeholder="请输入电话号码" v-model="phone" />
      </view>

      <!-- 省市区选择 -->
      <view class="form-item">
        <text class="label">城市</text>
        <picker mode="multiSelector" :range="regionData" :value="cityValue" @change="handleCityChange" @columnchange="handleColumnChange">
          <view class="picker-text">{{ cityLabel || '请选择城市' }}</view>
        </picker>
      </view>

      <!-- 详细地址 -->
      <view class="form-item">
        <text class="label">详细地址</text>
        <input class="input" placeholder="请输入详细地址" v-model="addressLine1" />
      </view>
    </view>

    <button class="save-button" @click="saveAddress">保存地址</button>
  </view>
</template>


<script>
import { data } from "@/api/data.js";  
import {SetAddress	} from '@/api/address.js';

export default {
  data() {
    return {
      name: "",
      phone: "",
			addressId:'',
      addressLine1: "",
      cityValue: [0, 0, 0],
      cityLabel: "",
      regionData: [
        [], // 省
        [], // 市
        [] // 区
      ],
    };
  },
  methods: {
    // 获取省市区的索引
    getRegionIndex(regionParts) {
      const provinceIndex = data.province.findIndex(province => province.name === regionParts[0]);
      const cityIndex = data.city.findIndex(city => city.name === regionParts[1] && city.provinceId === data.province[provinceIndex].id);
      const districtIndex = data.district.findIndex(district => district.name === regionParts[2] && district.cityId === data.city[cityIndex].id);

      return [provinceIndex, cityIndex, districtIndex];
    },

    // 初始化省市区数据
    initializeRegionData() {
      this.regionData[0] = data.province.map((province) => province.name);
      const firstProvinceId = data.province[0].id;
      this.regionData[1] = data.city.filter((city) => city.provinceId === firstProvinceId).map((city) => city.name);
      const firstCityId = data.city.find((city) => city.provinceId === firstProvinceId).id;
      this.regionData[2] = data.district.filter((district) => district.cityId === firstCityId).map((district) => district.name);
    },

    // 处理列变化
    handleColumnChange(event) {
      const { column, value } = event.detail;

      if (column === 0) {
        const selectedProvinceId = data.province[value].id;
        this.regionData[1] = data.city.filter((city) => city.provinceId === selectedProvinceId).map((city) => city.name);
        const firstCityId = data.city.find((city) => city.provinceId === selectedProvinceId).id;
        this.regionData[2] = data.district.filter((district) => district.cityId === firstCityId).map((district) => district.name);
        this.cityValue[1] = 0;
        this.cityValue[2] = 0;
      } else if (column === 1) {
        const selectedCityId = data.city.find(
          (city) => city.name === this.regionData[1][value]
        ).id;
        this.regionData[2] = data.district.filter((district) => district.cityId === selectedCityId).map((district) => district.name);
        this.cityValue[2] = 0;
      }
    },

    // 处理选择完成
    handleCityChange(event) {
      const [provinceIndex, cityIndex, districtIndex] = event.detail.value;
      const province = this.regionData[0][provinceIndex];
      const city = this.regionData[1][cityIndex];
      const district = this.regionData[2][districtIndex];
      this.cityLabel = `${province} ${city} ${district}`;
    },

    // 保存地址
    saveAddress() {
      if (!this.name || !this.phone || !this.addressLine1 || !this.cityLabel) {
        uni.showToast({
          title: "请填写完整信息",
          icon: "none"
        });
        return;
      }
      SetAddress({
        userId: parseInt(this.$cookies.get("id")),
        username: this.name,
        userphone: this.phone,
        provinceCityDistrict: this.cityLabel,
        fullAddress: this.addressLine1,
				addressId:this.addressId
      }).then((res) => {
          uni.showToast({
            title: "地址已保存",
            icon: "success"
          });
          this.name = "";
          this.phone = "";
          this.addressLine1 = "";
          this.cityLabel = "";
          this.cityValue = [0, 0, 0];
      
      }).catch(() => {
        uni.showToast({
          title: "更新失败，请稍后重试",
          icon: "none",
        });
      });
    },

    // onLoad 方法
    onLoad(options) {
      const address = JSON.parse(decodeURIComponent(options.address));
      console.log(address);
      this.name = address.username;
      this.phone = address.userphone;
      this.addressLine1 = address.fullAddress;
      this.addressId=address.addressId;
      if (address.provinceCityDistrict) {
        const regionParts = address.provinceCityDistrict.split(' ');
        this.cityLabel = address.provinceCityDistrict;
        this.cityValue = this.getRegionIndex(regionParts);  // 获取省市区的索引
      }
    },
  },
  mounted() {
    this.initializeRegionData(); // 初始化省市区数据
  },
};

</script>


<style>
	.container {
		padding: 16px;
		background-color: #fff;
	}

	.header {
		background-color: #2ac2d2;
		display: flex;
		align-items: center;
		padding: 15px 20px;
		color: #fff;
		width: 100%;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		border-radius: 10px;
		margin-bottom: 20px;
	}

	.header-title {
		font-size: px;
		font-weight: bold;
	}

	.form {
		margin-top: 16px;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 10px 0;
		border-bottom: 1px solid #f0f0f0;
	}

	.label {
		width: 90px;
		color: #333;
	}

	.input,
	.textarea {
		flex: 1;
		padding: 8px;
		border: none;
		background-color: #f9f9f9;
		border-radius: 4px;
	}

	.textarea {
		height: 80px;
	}

	.save-button {
		width: 100%;
		height: 40px;
		margin-top: 20px;
		background-color: #2ac2d2;
		color: #fff;
		text-align: center;
		line-height: 40px;
		border-radius: 4px;
	}
</style>